<?php

namespace app\admin\controller;

use app\admin\common\Base;
use think\Db;

class Inquiry extends Base {
    public function index($status='',$start_time='',$end_time='',$page = 1,$limit = 10){
        if (is_post()){
            if ($status == 1){
                $where[] = ['status','=',0];
            }elseif ($status == 2){
                $where[] = ['status','=',1];
            }

            if (!empty($start_time)){
                $start_time = strtotime($start_time);
                $end_time = strtotime($end_time);
                $where[] = ['create_time','between',[$start_time,$end_time]];
            }

            $where[] = ['is_del','=',0];
            $data = $this->getListData('inquiry',$where,'create_time','desc',$page,$limit);

            foreach ($data['list'] as $k => $v){
                $data['list'][$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }

            return json(['code'=>'suc','msg'=>'数据请求成功','data'=>$data['list'],'count'=>$data['count'],'current_page'=>$page]);
        }
        $this->assign('status',input('param.status'));
        return $this->fetch();
    }

    public function details($id){
        //修改询盘信息状态为已读
        Db::name('inquiry')->where('id',$id)->update(['status' => 1]);
        insert_system_log('设置询盘消息为已读。ID：' . $id);
        $info = Db::name('inquiry')
            ->where('id',$id)
            ->find();
        $info['create_time'] = date('Y-m-d H:i:s',$info['create_time']);
        $this->assign('info',$info);
        return $this->fetch();
    }

    /**
     * 设置为已读
     * @param $id
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setRead($id){
        if (is_post()){
            $result = Db::name('inquiry')
                ->where('id','in',$id)
                ->update(['status' => 1]);
            $id = implode(',',$id);
            if ($result){
                insert_system_log('设置询盘消息为已读。ID：' . $id);
                return json(['code' => 'suc','msg'=>'已设为已读']);
            }
            return json(['code' => 'err','msg'=>'系统繁忙，请重试']);
        }
    }

    /**
     * 全部设置已读
     * @return \think\response\Json
     */
    public function allRead(){
        //启动事务
        Db::startTrans();
        try{
            Db::name('inquiry')
                ->where('is_del',0)
                ->update(['status'=>1]);
            //提交事务
            Db::commit();
            insert_system_log('设置询盘消息为全部已读');
            return json(['code' => 'suc','msg'=>'已全部设为已读']);
        }catch (\Exception $e){
            //回滚事务
            Db::rollback();
            return json(['code' => 'err','msg'=>'系统繁忙，请重试']);
        }
    }

    public function del($id){
        $result = Db::name('inquiry')
            ->where('id','in',$id)
            ->update(['is_del' => 1]);

        if ($result){
            insert_system_log('删除询盘消息：' . implode(',',$id));
            return json(['code' => 'suc','msg'=>'已删除']);
        }
        return json(['code' => 'err','msg'=>'系统繁忙，请重试']);
    }

    public function changeReadStatus($id,$type){
        $data['status'] = 1;
        $msg = '已设置为已读';
        $log_msg = '设置询盘消息为已读：';

        if ($type == 2){
            $data['status'] = 0;
            $msg = '已设置为未读';
            $log_msg = '设置询盘消息为未读：';

        }

        $result = db('inquiry')->where('id',$id)->update($data);
        if ($result){
            insert_system_log($log_msg . $id);
            return json(['code' => 'suc','msg' => $msg]);
        }else{
            return json(['code' => 'err','msg' => '系统繁忙，请重试']);

        }
    }

    /**
     * 导出到Excel
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function exportExcel(){
        $list = Db::name('inquiry')
            ->where('is_del',0)
            ->order('create_time','desc')
            ->select();

        //实例化phpexcel
        $objPHPExcel = new \PHPExcel();

        $PHPSheet = $objPHPExcel->getActiveSheet();
        //设置表内部名称
        $PHPSheet->setTitle('询盘消息');

        $PHPSheet->setCellValue('A1','姓名')
            ->setCellValue('B1','邮箱')
            ->setCellValue('C1','内容')
            ->setCellValue('D1','发送日期')
            ->setCellValue('E1','状态');

        $num = 2;

        foreach ($list as $k => $v){
            $PHPSheet->setCellValue("A" . $num, $v['name']);
            $PHPSheet->setCellValue('B'. $num,$v['email']);
            $PHPSheet->setCellValue('C'. $num,$v['message']);
            $PHPSheet->setCellValue('D'. $num,date('Y-m-d H:i:s',$v['create_time']));
            $PHPSheet->setCellValue('E'. $num,$v['status'] == 1 ? '已读' : '未读');
            $num++;
        }

        $PHPWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');
        header('Content-Disposition: attachment;filename="询盘消息'.date("YmdHis",time()).'.xlsx"');//下载下来的表格名
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $PHPWriter->save("php://output");
    }
}